package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.zookeeper.server.quorum.Follower;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class VideoService {
    @Reference
    private VideoApi videoApi;
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
@CacheEvict(value = "videoList",allEntries = true)
    public void post(MultipartFile videoThumbnail, MultipartFile videoFile) {
        Long longinUserId = UserHolder.getUserId();
        //调用阿里云上传图片
        try {
            String videoThumbnailUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            InputStream inputStream = videoFile.getInputStream();
            String originalFilename = videoFile.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            StorePath storePath = client.uploadFile(inputStream, videoFile.getSize(), substring, null);
            //获取文件请求地址
            String url = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
            System.out.println(url);
            Video video = new Video();
            video.setPicUrl(videoThumbnailUrl);
            video.setVideoUrl(url);
            video.setText("马广五出品");
            video.setUserId(longinUserId);
            videoApi.post(video);
        } catch (IOException e) {
            // e.printStackTrace();
            log.info("视频或封面上传失败");
            throw new TanHuaException("视频或封面上传失败");
        }
    }
    @Cacheable(value = "videoList", key = "'_'+ #page+'_'+#pageSize")
    public PageResult<VideoVo> getVideo(Long page, Long pagesize) {
        PageResult pageResult = videoApi.findPage(page, pagesize);
        List<Video> items = pageResult.getItems();
        List<VideoVo> videoVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(items)) {
            List<Long> userIds = items.stream().map(Video::getUserId).collect(Collectors.toList());
            List<UserInfo> userInfos = userInfoApi.findByBatchIds(userIds);
            Map<Long, UserInfo> userInfiMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getId, u -> u));
            List<VideoVo> videoVoList = items.stream().map(video -> {
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(video, vo);
                UserInfo userInfo = userInfiMap.get(video.getUserId());
                BeanUtils.copyProperties(userInfo, vo);
                vo.setId(video.getId().toHexString());
                vo.setSignature(video.getText());
                vo.setCover(video.getPicUrl());
                String key = "follow_user_" + UserHolder.getUserId() + "_" + video.getUserId();
                if (stringRedisTemplate.hasKey(key)) {
                    vo.setHasFocus(1);
                }
                return vo;
            }).collect(Collectors.toList());
           pageResult.setItems(videoVoList);
        }
        return pageResult;
    }
    @CacheEvict(value = "videoList", allEntries = true)
    public void userFocus(Long smallVideoId) {
        Long loginUserId = UserHolder.getUserId();
        if (loginUserId.equals(smallVideoId)){
            throw new TanHuaException("不能关注自己");
        }
        FollowUser followUser = new FollowUser();
        followUser.setUserId(loginUserId);
        followUser.setFollowUserId(smallVideoId);
        videoApi.userFocus(followUser);
        String key = "follow_user_" + loginUserId + "_" + smallVideoId;
        stringRedisTemplate.opsForValue().set(key,"1");
    }
    @CacheEvict(value = "videoList", allEntries = true)
    public void userUnFocus(Long smallVideoId) {
        Long loginUserId = UserHolder.getUserId();
        FollowUser followUser = new FollowUser();
        followUser.setUserId(loginUserId);
        followUser.setFollowUserId(smallVideoId);
        videoApi.userUnFocus(followUser);
        String key = "follow_user_" + loginUserId + "_" + smallVideoId;
        stringRedisTemplate.delete(key);
    }
}
